package net.hyperz.showtime.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBProvider {
	private static final String DATABASE_NAME = "showtime.db";
	private static final int DATABASE_VERSION = 1;
	private Context ctx = null;
	private SQLiteDatabase DBInstance;
	
	public DBProvider(Context context) {
		ctx = context;
	}
	
	//---opens the database---
	public DBProvider open() throws SQLException 
	{
		boolean getDatabase = false;
		
		try {
			OpenHelper oh = new OpenHelper(this.ctx);
			if (DBInstance == null) {
					getDatabase = true;
			} else {
				if (!DBInstance.isOpen()) {
					getDatabase = true;
				}
			}
			
			if (getDatabase) {
				DBInstance = oh.getWritableDatabase();
				DBInstance.setLockingEnabled(false);
			}
			
			return this;
		}
		catch (SQLiteException sqlE) {
			Log.e("DBProvider", "SQLLiteException", sqlE);
			return null;
		}
		catch (Exception ex) {
			Log.e("DBProvider", "SQLLiteException", ex);
			return null;
		}
	}
	
	//---closes the database---
	public void close() 
	{
		if (DBInstance != null) {
			if (DBInstance.isOpen()) {
				SQLiteDatabase.releaseMemory();
				DBInstance.close();
			}
		}
	}
	
	private class OpenHelper extends SQLiteOpenHelper {
		public OpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		
		@Override
		public void onOpen(SQLiteDatabase dbInstance) {
			dbInstance.setVersion(DATABASE_VERSION);
		}
		
		//Create all the tables
		@Override
		public void onCreate(SQLiteDatabase dbInstance) {
			dbInstance.execSQL("CREATE TABLE Provider ( " +
					"ID        INTEGER PRIMARY KEY AUTOINCREMENT," +
					"PostCode  TEXT," +
					"ZapID     TEXT," +
					"Name      TEXT);");
			
			dbInstance.execSQL("CREATE TABLE Network ( " +
				    "ID          INTEGER PRIMARY KEY AUTOINCREMENT," +
					"Logo        BLOB," +
				    "LogoLink    TEXT," +
				    "Name        TEXT," +
				    "ZapID       TEXT," +
					"CallSign    TEXT);");
			
			dbInstance.execSQL("CREATE TABLE Channel ( " +
					"ID          INTEGER PRIMARY KEY AUTOINCREMENT," +
					"Number      NUMBER," +
					"NetworkID   INTEGER REFERENCES Network ( ID )," +
					"ProviderID  INTEGER REFERENCES Provider ( ID ));");
			
			dbInstance.execSQL("CREATE TABLE HTMLStorage (" + 
					"ID			INTEGER PRIMARY KEY AUTOINCREMENT," +
					"Timestamp  NUMBER," +
					"Data       BLOB," +
					"ProviderID INTEGER REFERENCES Provider ( ID ));");
			
			SQLiteDatabase.releaseMemory();
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase dbInstance, int oldVersion, int newVersion) {
			//for now just drop and recreate!
			//TODO: A proper DB upgrade, involving from which version the upgrade is being 
			// performed from and which database version it's being upgraded too.
			switch (oldVersion) {
			case 1:
			default:
				
				dbInstance.execSQL("DROP TABLE IF EXISTS Network");
				dbInstance.execSQL("DROP TABLE IF EXISTS Provider");
				dbInstance.execSQL("DROP TABLE IF EXISTS Channel");
				
				onCreate(dbInstance);

				break;
			}

			SQLiteDatabase.releaseMemory();
		}
	}
	
	
	//---checks if the cursor is not null and moves to first record
	public boolean isValidCursor(Cursor cur) {
		if (cur != null) {
			if (cur.moveToFirst()) {
				return true;
			}
		}
		
		return false;
	}
	
	public int update(String tableName, ContentValues values, String whereClause, String... whereArgs) {
		return DBInstance.update(tableName, values, whereClause, whereArgs);
	}
	
	public long insert(String tableName, ContentValues values) {
		return DBInstance.insert(tableName, null, values);
	}
	
	public int delete(String tableName, String whereClause, String... whereArgs) {
		return DBInstance.delete(tableName, whereClause, whereArgs);
	}
	
	public Cursor select(String query, String[] queryArgs) {
		return DBInstance.rawQuery(query, queryArgs);
	}
}
